package com.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;

/**
 * @author Lee
 */
public class ImageToChar {
    /**
     * 此处设置灰度字符，此处只用十个字符，可以设置更多
     */
    private static final char[] CS = new char[] { '.', '&', '*', '@', '=', ',', '$', '+', '#', ' ' };

    public static void main(String[] args) throws IOException {
        // 读取图片
        BufferedImage bufferedImage = ImageIO.read(new File("D:\\a.png"));
        // 图片转字符串后的数组
        char[][] css = new char[bufferedImage.getWidth() / 2][bufferedImage.getHeight() / 2];
        for (int x = 0; x < bufferedImage.getWidth(); x++) {
            if (x % 2 != 0) {
                continue;
            }
            for (int y = 0; y < bufferedImage.getHeight(); y++) {
                if (y % 2 != 0) {
                    continue;
                }
                int rgb = bufferedImage.getRGB(x, y);
                Color c = new Color(rgb);
                // 得到灰度值
                int cc = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
                css[x / 2][y / 2] = CS[(cc * 10 - 1) / 255];
            }
        }
        StringBuilder sb = new StringBuilder();
        // 开始拼接内容
        for (int y = 0; y < css[0].length; y++) {
            for (char[] chars : css) {
                sb.append(chars[y]);
            }
            sb.append("\r\n");
        }
        System.out.println(sb.toString());
        // 生成文件
        writeFile(new File("D:\\content.txt"), sb.toString(), "utf-8");
    }

    /**
     * 写文件
     */
    public static void writeFile(File file, String string, String encoding) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] bs = string.getBytes(encoding);
            fos.write(bs);
        }
    }
}